#coding: utf-8
#access data interface and implements

#data format:
#date: 4bytes "yyyymmdd" in decial
#open_price(1000 times): 4bytes
#highest_price(1000 times): 4bytes
#lowest_price(1000 times): 4bytes
#close_price(1000 times): 4bytes
#amount(shou): 4bytes
#total(yuan): 4bytes
#unused: 12bytes

ROOT = r"C:\lonwdip\QLDATA\history"
DAY_FMT = r"10I"
CODE_PAT = "(s[h|z])(\d\d\d\d\d\d)$"

import sys, os, struct, re
import scipy, pylab
import datetime, time

def readfmt(f, fmt):
    sz = struct.calcsize(fmt)
    s = f.read(sz)
    if len(s)==sz:
        return struct.unpack(fmt, s)
    else:
        return None

def get_daypath_ql(code):
    match = re.match(CODE_PAT, code)
    assert match, "code should be 'shnnnnnn' or 'sznnnnnn'."
    market, ncode = match.groups()
    market_dir = {'sh' : 'shase', 'sz' : 'sznse'}[market]
    return os.path.join(ROOT, market_dir, "day", "%s.day" % ncode)

def read_raw(code, get_daypath):
    data = []
    p = get_daypath(code)
    f = file(p, "rb")
    count = 0
    while 1:
        r = readfmt(f, DAY_FMT)
        if not r:
            break
        trade_date, open_price, highest_price, lowest_price, close_price, amount, total, unused, unused, unused = r
        t = time.mktime((trade_date/10000, (trade_date[0]/100)%100, trade_date%100,0,0,0,0,0,0))
        data.append([r[0], r[1]/1000.0])
        #print t,
        #print r
        count += 1
    
    f.close()
    return data

def test(code="sh601600"):
    #test get data
    data = read_raw(code, get_daypath_ql)

    #x, y = scipy.transpose(data[-30:])
    x, y = scipy.transpose(data[-300:])
    pylab.plot(y)
    pylab.show()

if __name__ == '__main__':
    #test("sh500011")
    test("sh000001")